<template>
  <div class="utool" :class="{ compare: compare }">
    <div class="utool-t">
      <!-- 图层 底图 图例 -->
      <div
        class="utool-t-option"
        v-for="item in t"
        :key="item.icon"
        :style="{
          color:
            (activeOptionData === 'shujufuwu' &&
              item.icon === 'shujufuwu') ||
            activeOption === item.icon
              ? activeColor
              : defaultColor
        }"
      >
        <div @click="toggle(item.icon)">
          <Icon
            :title="item.title"
            :name="item.icon"
            :font-size="iconSize"
          />
          <span>{{ item.title }}</span>
        </div>
        <component
          :is="activeOption"
          v-if="activeOption === item.icon"
          class="layerManage"
        />
      </div>
      <!-- 距离 高度 面积 清空 -->
      <div
        @click="toggle(item.icon)"
        class="utool-t-option"
        v-for="item in c"
        :key="item.title"
        :style="{
          color:
            activeOption === item.icon
              ? activeColor
              : defaultColor
        }"
      >
        <Icon
          :title="item.title"
          :name="item.icon"
          :font-size="iconSize"
        />
      </div>
      <!-- 更多 -->
      <div
        class="utool-t-option"
        :style="{
          color:
            activeOption === more.icon
              ? activeColor
              : defaultColor
        }"
      >
        <div @click="toggle(more.icon)">
          <Icon
            :title="more.title"
            :name="more.icon"
            :font-size="iconSize"
          />
        </div>
        <Auxiliary
          :options="auxiliaryOptions"
          @changeActive="changeActive"
          v-if="activeOption === more.icon"
          class="auxiliary"
        />
      </div>
    </div>
    <div class="utool-b">
      <div
        class="utool-b-option"
        v-for="item in b"
        :key="item.title"
        :style="{
          color:
            activeOption === item.icon
              ? activeColor
              : defaultColor
        }"
      >
        <div @click="toggle(item.icon)">
          <Icon
            :title="item.title"
            :name="item.icon"
            :font-size="iconSize"
          />
        </div>
        <component
          :is="activeOption"
          v-if="activeOption === item.icon"
          class="bottomManage"
        />
      </div>
    </div>
    <component
      @close="activeTool = ''"
      :class="
        ['biaoji', 'changjing', 'keng'].indexOf(
          activeTool
        ) !== -1
          ? 'utool-biaoji-position compare-biaoji-position'
          : 'utool-position compare-position'
      "
      :is="activeTool"
    />
    <FlyLineControl
      v-if="showFlyLineControl"
      :compare="compare"
    />
  </div>
</template>

<script>
import Icon from '@/components/icon'
import Auxiliary from './components/auxiliary'
import BaseMap from './components/baseMap'
import Terrain from './components/terrain'
import Tuli from './components/legend'
import Changjing from './components/sceneStyle'
import LayerManage from './components/layerManage'
import Dingwei from './components/location'
import Shijiaoqiehuan from './components/cameraLock'
import Manyou from './components/flyLine'
import Dixiamoshi from './components/underground'
import FlyLineControl from './components/flyLineControl'
import Fanwei from './components/tools/fanwei'
import Keng from './components/tools/cutfill'
import {
  Clipplane as Moxing,
  Measure as Celiang,
  Sightline as Tongshi,
  Skyline as Tianjixian,
  Sunshine as Rizhao,
  Viewfield as Shiyu,
  Mark as Biaoji
} from './components/tools'
import { getAction } from '@/utils/helper'
import { homePosition } from '@/utils/constant'
import cacheUtil from '@/utils/cache'

const mapViewer = {}
const measure = {}

export default {
  props: {
    compare: {
      type: Boolean,
      default: false
    },
    viewerId: {
      type: String,
      default: ''
    },
    mapKey: {
      type: String,
      default: 'viewer'
    }
  },
  provide() {
    return {
      viewerId: this.viewerId
    }
  },
  components: {
    Icon,
    Auxiliary,
    Celiang,
    Moxing,
    Biaoji,
    Rizhao,
    Tianjixian,
    Tongshi,
    Shiyu,
    LayerManage,
    Terrain,
    BaseMap,
    Tuli,
    Changjing,
    Dingwei,
    Shijiaoqiehuan,
    Manyou,
    Dixiamoshi,
    FlyLineControl,
    Fanwei,
    Keng
  },
  data() {
    return {
      t: [
        {
          title: '数据',
          icon: 'shujufuwu'
        },
        {
          title: '图层',
          icon: 'layerManage'
        },
        {
          title: '底图',
          icon: 'baseMap'
        }
        // {
        //   title: '地形',
        //   icon: 'terrain'
        // },
        // {
        //   title: '图例',
        //   icon: 'tuli'
        // }
      ],
      c: [
        {
          title: '测距',
          icon: 'juli'
        },
        {
          title: '测高',
          icon: 'gaodu'
        },
        {
          title: '测面',
          icon: 'mianji'
        },
        {
          title: '清除',
          icon: 'qingchu'
        }
      ],
      b: [
        {
          title: '初始位置',
          icon: 'dingwei'
        },
        {
          title: '视角切换',
          icon: '3d'
        },
        {
          title: '漫游',
          icon: 'manyou'
        },
        {
          title: '地下模式',
          icon: 'dixiamoshi'
        }
      ],
      auxiliaryOptions: [
        {
          title: '测量工具',
          icon: 'celiang'
        },
        {
          title: '地图标注',
          icon: 'biaoji'
        },
        {
          title: '模型剖切',
          icon: 'moxing'
        },
        {
          title: '日照分析',
          icon: 'rizhao'
        },
        {
          title: '通视分析',
          icon: 'tongshi'
        },
        {
          title: '视域分析',
          icon: 'shiyu'
        },
        {
          title: '天际线分析',
          icon: 'tianjixian'
        },
        {
          title: '场景模拟',
          icon: 'changjing'
        },
        {
          title: '挖填方分析',
          icon: 'keng'
        },
        {
          title: '范围上传',
          icon: 'fanwei'
        }
      ],
      more: { title: '更多', icon: 'gengduo' },
      activeTool: '',
      activeOption: '',
      activeOptionData: 'shujufuwu',
      activeColor: 'rgba(0, 210, 255, 1)',
      defaultColor: '#D2E6F0',
      iconSize: 22,
      showFlyLineControl: false,
      showDataTree: false,
      cameraConfig: null
    }
  },
  async mounted() {
    const { viewer, toolManager } = await getAction(
      this.viewerId
    )
    mapViewer[this.viewerId] = viewer
    measure[this.viewerId] = toolManager.measure

    this.$bus.$on('flyLineStart', () => {
      this.showFlyLineControl = true
    })
    this.$bus.$on('flyLineStop', () => {
      this.showFlyLineControl = false
    })

    const cacheItem = cacheUtil.getItem('camera')
    if (cacheItem) {
      try {
        const config = JSON.parse(cacheItem)
        if (config.cameraHeight && config.centerPoint) {
          this.cameraConfig = config
        }
      } catch (e) {
        console.error(e)
      }
    }
  },
  methods: {
    toggle(icon) {
      this.activeTool = ''
      if (icon === 'qingchu') {
        // measure[this.viewerId].inactive()
        measure[this.viewerId].clear()
        this.activeOption = ''
      } else if (icon === 'shujufuwu') {
        if (this.activeOptionData === icon) {
          this.activeOptionData = ''
        } else {
          this.activeOptionData = icon
        }
        this.showDataTree = !this.showDataTree
        this.$emit('showData', this.showDataTree)
      } else if (icon === 'layerManage') {
        if (this.activeOption === icon) {
          this.activeOption = ''
          this.activeOptionData = 'shujufuwu'
          this.$emit('showData', false)
        } else {
          this.activeOption = icon
          this.activeOptionData = ''
          this.$emit('showData', true)
        }
      } else if (
        icon === 'juli' ||
        icon === 'gaodu' ||
        icon === 'mianji'
      ) {
        if (this.activeOption === icon) {
          this.activeOption = ''
          // measure[this.viewerId].inactive()
          measure[this.viewerId].clear()
        } else {
          this.activeOption = icon
          switch (icon) {
            case 'juli':
              // measure[this.viewerId].inactive()
              measure[this.viewerId].clear()
              measure[this.viewerId].length()
              break
            case 'gaodu':
              // measure[this.viewerId].inactive()
              measure[this.viewerId].clear()
              measure[this.viewerId].height()
              break
            case 'mianji':
              // measure[this.viewerId].inactive()
              measure[this.viewerId].clear()
              measure[this.viewerId].area()
              break
            default:
              break
          }
        }
      } else if (icon === 'dingwei') {
        mapViewer[this.viewerId].camera.flyTo({
          destination: this.cameraConfig
            ? Cesium.Cartesian3.fromDegrees(
                Number(
                  this.cameraConfig.centerPoint.split(
                    ','
                  )[0]
                ),
                Number(
                  this.cameraConfig.centerPoint.split(
                    ','
                  )[1]
                ),
                Number(this.cameraConfig.cameraHeight)
              )
            : homePosition.destination,
          orientation: homePosition.orientation
        })
      } else if (icon === '2d') {
        this.activeOption = ''
        // mapViewer[this.viewerId].scene.mode =
        //   Cesium.SceneMode.SCENE3D
        mapViewer[
          this.viewerId
        ].scene.screenSpaceCameraController.enableTilt = true
        this.b[1].icon = '3d'
      } else if (icon === '3d') {
        this.activeOption = ''
        this.b[1].icon = '2d'
        // mapViewer[this.viewerId].scene.mode =
        //   Cesium.SceneMode.SCENE2D
        this.viewFromTop()
        mapViewer[
          this.viewerId
        ].scene.screenSpaceCameraController.enableTilt = false
      } else {
        if (this.activeOption === icon) {
          this.activeOption = ''
        } else {
          this.activeOption = icon
        }
      }
    },
    changeActive(icon) {
      console.log(icon)
      this.activeOption = ''
      this.activeOptionData = ''
      this.$emit('showData', true)
      this.activeTool = icon
    },
    // 切换顶部视角
    viewFromTop() {
      const centerResult = mapViewer[
        this.viewerId
      ].camera.pickEllipsoid(
        new Cesium.Cartesian2(
          mapViewer[this.viewerId].canvas.clientWidth / 2,
          mapViewer[this.viewerId].canvas.clientHeight / 2
        )
      )
      console.log('centerResult', centerResult)
      const curPosition =
        Cesium.Ellipsoid.WGS84.cartesianToCartographic(
          centerResult
        )
      console.log('curPosition', curPosition)
      const curLongitude =
        (curPosition.longitude * 180) / Math.PI
      const curLatitude =
        (curPosition.latitude * 180) / Math.PI
      console.log('当前中心点', curLongitude, curLatitude)
      mapViewer[this.viewerId].scene.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(
          curLongitude,
          curLatitude,
          8000.0
        ),
        orientation: {
          heading: Cesium.Math.toRadians(0),
          pitch: Cesium.Math.toRadians(-90),
          roll: 0.0
        },
        duration: 1
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.utool {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20px;

  &-t {
    width: 100%;

    &-option:nth-child(3) {
      border-bottom: 1px solid rgba(255, 255, 255, 0.2);
    }

    &-option {
      position: relative;
      width: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 6px 0;

      & > div {
        display: flex;
        flex-direction: column;
        align-items: center;

        & > span {
          cursor: pointer;
          font-size: 12px;
        }
      }

      & > span {
        cursor: pointer;
        font-size: 12px;
      }
    }
  }

  &-b {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;

    &-option {
      position: relative;
      width: 100%;

      .bottomManage {
        left: calc(100% + 13px);
      }
    }

    & > div {
      width: 38px;
      height: 38px;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 4px;

      &:hover {
        background: #00baff;
      }

      &:not(:first-child) {
        margin-top: 10px;
      }

      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      & > span {
        font-size: 12px;
      }
    }

    &-option {
    }
  }

  &-position {
    position: fixed !important;
    top: 80px;
    left: 50%;
    transform: translateX(50%);
  }

  &-biaoji-position {
    position: absolute;
    top: 20px;
    left: 65px;
  }
}

.compare {
  padding-bottom: 0;

  .utool-t {
    background: #192f3d;
    border-radius: 4px;
  }

  .utool-b {
    & > div {
      width: 38px;
      height: 38px;
      background: #192f3d;
      border-radius: 4px;

      &:hover {
        background: #00baff;
      }

      &:not(:first-child) {
        margin-top: 10px;
      }
    }
  }

  .compare-position {
    position: absolute;
    top: 10px;
    left: calc(25vw - 110px);
    transform: translateX(50%);
  }
}

.layerManage {
  position: absolute;
  left: calc(100% + 8px);
  top: 10px;
}

.bottomManage {
  position: absolute;
  left: calc(100% + 8px);
  bottom: 0;
}

.auxiliary {
  position: absolute;
  left: calc(100% + 8px);
  top: 0;
}
</style>
